#include "deptmanagerapi.h"

DeptManagerApi::DeptManagerApi(QObject *parent)
    : QObject{parent}
{
    baseUrl = Config::baseUrl;
    manager = new QNetworkAccessManager(0);
    request.setHeader(QNetworkRequest::ContentTypeHeader,QVariant("application/json"));//post请求设置为json，才能发送josn格式文件
    request.setRawHeader("Authorization",  qApp->property("token").value<QString>().toLocal8Bit());

}

QByteArray *DeptManagerApi::list(QString deptName, QString status)
{
    QString params = "system/dept/list?";
    if(!deptName.isEmpty()){
        params += "deptName=" + deptName;
    }
    if(!status.isEmpty()){
        params += "&status=" + status;
    }
    request.setUrl(baseUrl + params);
    QNetworkReply *reply= manager->get(request);
    //同步请求
    QEventLoop eventLoop;
    connect(reply, &QNetworkReply::finished, &eventLoop, &QEventLoop::quit);
    eventLoop.exec();
    data = new QByteArray(reply->readAll().data());
    reply->deleteLater();
    utils.requestCheck(data);
    return data;
}

QByteArray *DeptManagerApi::editDept(int deptId, Dept &dept)
{
    request.setUrl(baseUrl + "system/dept");
    QJsonObject obj = dept.toJsonObject();
    QByteArray arr = QJsonDocument(obj).toJson();
    QNetworkReply *reply = deptId > 0 ? manager->put(request,arr) : manager->post(request,arr);
    //同步请求
    QEventLoop eventLoop;
    connect(reply, &QNetworkReply::finished, &eventLoop, &QEventLoop::quit);
    eventLoop.exec();
    data = new QByteArray(reply->readAll().data());
    reply->deleteLater();
    utils.requestCheck(data);
    return data;
}

QByteArray *DeptManagerApi::getById(int deptId)
{
    request.setUrl(baseUrl + "system/dept/" + QString::number(deptId));
    QNetworkReply *reply = manager->get(request);
    //同步请求
    QEventLoop eventLoop;
    connect(reply, &QNetworkReply::finished, &eventLoop, &QEventLoop::quit);
    eventLoop.exec();
    data = new QByteArray(reply->readAll().data());
    reply->deleteLater();
    utils.requestCheck(data);
    return data;
}

QByteArray *DeptManagerApi::deleteById(int deptId)
{
    request.setUrl(baseUrl + "system/dept/" + QString::number(deptId));
    QNetworkReply *reply = manager->deleteResource(request);
    //同步请求
    QEventLoop eventLoop;
    connect(reply, &QNetworkReply::finished, &eventLoop, &QEventLoop::quit);
    eventLoop.exec();
    data = new QByteArray(reply->readAll().data());
    reply->deleteLater();
    utils.requestCheck(data);
    return data;
}
